<?php

/**
 *
 *
 *
 * @package lib.model
 * @author r9jason
 */
class GoldTradingService
{
    public function fetchGoldSell()
    {
        $goldSell = 0;
        $c = new Criteria();
        $c->addDescendingOrderByColumn(MlmGoldPriceHistoryPeer::CREATED_ON);
        $exist = MlmGoldPriceHistoryPeer::doSelectOne($c);
        if ($exist) $goldSell = $exist->getGoldPrice();

        return number_format($goldSell, 4);
    }

    public function fetchGoldBuy($goldSell = null)
    {
        if ($goldSell == null) {
            $goldSell = $this->fetchGoldSell();
        }
        $goldBuy = $goldSell - 0.2;

        return $goldBuy;
    }

    public function fetchAllTradingData($distributorId)
    {
        $goldTradingDto = new GoldTradingDto();
        if (isset($distributorId) && trim($distributorId) != '') {
            $paperQuantity = 0;
            $averagePriceBuy = 0;
            $unrealizedProfitLoss = 0;
            $tradingPoint = 0;
            $currentGoldPrice = 0;
            $companyBuyGoldPrice = 0;

            /**********************************/
            // gold Price
            /**********************************/
            $currentGoldPrice = $this->fetchGoldSell();
            $companyBuyGoldPrice = $this->fetchGoldBuy();

            /*************************************/
            // paperQuantity
            /*************************************/
            $query = "SELECT SUM(buy_gram - sell_gram) AS SUB_TOTAL FROM mlm_egold_account
                    WHERE dist_id = " . $distributorId;

            $connection = Propel::getConnection();
            $statement = $connection->prepareStatement($query);
            $resultset = $statement->executeQuery();

            if ($resultset->next()) {
                $arr = $resultset->getRow();
                if ($arr["SUB_TOTAL"] != null) {
                    $paperQuantity = $arr["SUB_TOTAL"];
                }
            }

            /**********************************/
            // averagePriceBuy
            /**********************************/
            $c = new Criteria();
            $c->add(MlmDistEshareAccountPeer::DIST_ID, $distributorId);
            $c->addAnd(MlmDistEshareAccountPeer::SHARE_BALANCE, 0, Criteria::NOT_EQUAL);
            $c->addAnd(MlmDistEshareAccountPeer::STATUS_CODE, Globals::ESHARE_ACCOUNT_STATUS_ACTIVE, Criteria::EQUAL);
            $distEshareAccounts = MlmDistEshareAccountPeer::doSelect($c);

            $total = 0;
            $totalOriPrice = 0;
            if (count($distEshareAccounts) > 0) {
                foreach ($distEshareAccounts as $distEshareAccount) {
                    $total += $distEshareAccount->getCredit();
                    $totalOriPrice += ($distEshareAccount->getCredit() * $distEshareAccount->getBuyPrice());
                }

                if ($totalOriPrice != 0) {
                    $averagePriceBuy = $totalOriPrice / $total;
                }
            }
            //            var_dump($total);
            //            var_dump($totalOriPrice);
            //            exit();
            /**********************************/
            // unrealizedProfitLoss
            /**********************************/
            $unrealizedProfitLoss = ($currentGoldPrice - $averagePriceBuy) * $paperQuantity;

            /**********************************/
            // tradingPoint
            /**********************************/
            $query = "SELECT SUM(credit-debit) AS SUB_TOTAL FROM mlm_account_ledger
            WHERE dist_id = " . $distributorId . " AND account_type = '" . Globals::ACCOUNT_TYPE_TRADING_POINT . "'";

            $connection = Propel::getConnection();
            $statement = $connection->prepareStatement($query);
            $resultset = $statement->executeQuery();

            if ($resultset->next()) {
                $arr = $resultset->getRow();
                if ($arr["SUB_TOTAL"] != null) {
                    $tradingPoint = $arr["SUB_TOTAL"];
                }
            }

            $goldTradingDto->setPaperQuantity($paperQuantity);
            $goldTradingDto->setAveragePriceBuy($averagePriceBuy);
            $goldTradingDto->setUnrealizedProfitLoss($unrealizedProfitLoss);
            $goldTradingDto->setTradingPoint($tradingPoint);
            $goldTradingDto->setCurrentGoldPrice($currentGoldPrice);
            $goldTradingDto->setCompanyBuyGoldPrice($companyBuyGoldPrice);
        }

        /* *******************************
         *      e-Gold Information
         * *******************************/
        $dailyTradingVolumeBuy = 0;
        $dailyTradingVolumeSell = 0;
        $monthlyTradingVolumeBuy = 0;
        $monthlyTradingVolumeSell = 0;

        $dateUtil = new DateUtil();
        $currentDate = $dateUtil->formatDate("Y-m-d", date("Y-m-d"));

        $query = "SELECT SUM(debit) AS SUB_TOTAL FROM mlm_account_ledger
                WHERE account_type IN ('" . Globals::ACCOUNT_TYPE_ECASH . "','" . Globals::ACCOUNT_TYPE_MAINTENANCE . "') AND transaction_type ='" . Globals::ACCOUNT_LEDGER_ACTION_BUY_EGOLD . "'";
        $query .= " AND created_on >= '" . $currentDate . " 00:00:00'";
        $query .= " AND created_on <= '" . $currentDate . " 23:59:59'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                $dailyTradingVolumeBuy = $arr["SUB_TOTAL"];
            }
        }
        $query = "SELECT SUM(credit) AS SUB_TOTAL FROM mlm_account_ledger
                WHERE account_type IN ('" . Globals::ACCOUNT_TYPE_ECASH . "') AND transaction_type ='" . Globals::ACCOUNT_LEDGER_ACTION_SELL_EGOLD . "'";
        $query .= " AND created_on >= '" . $currentDate . " 00:00:00'";
        $query .= " AND created_on <= '" . $currentDate . " 23:59:59'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                $dailyTradingVolumeSell = $arr["SUB_TOTAL"];
            }
        }

        $d = $dateUtil->getMonth();
        $firstOfMonth = date('Y-m-j', $d["first_of_month"]) . " 00:00:00";
        $lastOfMonth = date('Y-m-j', $d["last_of_month"]) . " 23:59:59";

        $query = "SELECT SUM(debit) AS SUB_TOTAL FROM mlm_account_ledger
                WHERE account_type IN ('" . Globals::ACCOUNT_TYPE_ECASH . "','" . Globals::ACCOUNT_TYPE_MAINTENANCE . "') AND transaction_type ='" . Globals::ACCOUNT_LEDGER_ACTION_BUY_EGOLD . "'";
        $query .= " AND created_on >= '" . $firstOfMonth . "'";
        $query .= " AND created_on <= '" . $lastOfMonth . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                $monthlyTradingVolumeBuy = $arr["SUB_TOTAL"];
            }
        }
        $query = "SELECT SUM(credit) AS SUB_TOTAL FROM mlm_account_ledger
                WHERE account_type IN ('" . Globals::ACCOUNT_TYPE_ECASH . "') AND transaction_type ='" . Globals::ACCOUNT_LEDGER_ACTION_SELL_EGOLD . "'";
        $query .= " AND created_on >= '" . $firstOfMonth . "'";
        $query .= " AND created_on <= '" . $lastOfMonth . "'";

        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["SUB_TOTAL"] != null) {
                $monthlyTradingVolumeSell = $arr["SUB_TOTAL"];
            }
        }

        $goldTradingDto->setDailyTradingVolumeBuy($dailyTradingVolumeBuy);
        $goldTradingDto->setDailyTradingVolumeSell($dailyTradingVolumeSell);
        $goldTradingDto->setMonthlyTradingVolumeBuy($monthlyTradingVolumeBuy);
        $goldTradingDto->setMonthlyTradingVolumeSell($monthlyTradingVolumeSell);

        return $goldTradingDto;
    }

    function format2decimal($d)
    {
        return ceil($d * 100) / 100;
    }
}
